package org.gnyxy.controller.common;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.gnyxy.config.AliOSSConfig;
import org.gnyxy.constant.MessageConstant;
import org.gnyxy.exception.BaseException;
import org.gnyxy.result.Result;
import org.gnyxy.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/upload")
@Api(tags = "前后台通用-上传接口")
public class UploadController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping
    @ApiOperation("上传接口")
    public Result<String> upload(MultipartFile file) {
        log.info("上传文件: {}",file);
        // 判断是否为空
        if (file.isEmpty()){
            throw new BaseException(MessageConstant.UPLOAD_FILES_IS_NULL);
        }

        try {
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            // 分割 .
//            assert originalFilename != null;
            if (originalFilename == null){
                throw new BaseException(MessageConstant.UPLOAD_FAILED);
            }
            String[] split = originalFilename.split("\\.");
            if (split.length == 0){
                throw new BaseException(MessageConstant.UPLOAD_FAILED);
            }
            // 获取后缀名
            String lastName = split[split.length - 1];
            // 生成唯一名称
            String OnlyOneName = UUID.randomUUID() + "." + lastName;
            String upload = aliOssUtil.upload(file.getBytes(), OnlyOneName);
            return Result.success(upload);
        } catch (Exception e) {
            log.error(MessageConstant.UPLOAD_FAILED,e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
